#!/bin/bash

readonly reset=$(tput sgr0)
readonly red=$(tput bold; tput setaf 1)
readonly green=$(tput bold; tput setaf 2)

exit_code=0
goimports_available=false
gulp_available=false

# Pre checks
echo -ne "Checking if gulp is available... "
if ! OUT=$(ls node_modules/.bin/gulp 2>&1); then
  echo "${red}ERROR!"
  echo "${red}${OUT}"
  exit_code=1
else
  gulp_available=true
  echo "${green}OK"
fi

echo "${reset}"
echo -ne "Checking if goimports is available in your PATH... "
if ! OUT=$(which goimports 2>&1); then
  echo "${red}ERROR!"
  echo "Please add goimports to your PATH"
  exit_code=1
else
  goimports_available=true
  echo "${green}OK"
fi

if ${gulp_available}; then
  echo "${reset}"
  echo -ne "Checking javascript formatting... "
  if ! OUT=$(node_modules/.bin/gulp check-javascript-format 2>&1); then
    echo "${red}ERROR!"
    echo "There is an issue with file formatting."
    echo "To format javascript files run:"
    echo "  ./node_modules/.bin/gulp format-javascript"
    exit_code=1
  else
    echo "${green}OK"
  fi
fi

if ${goimports_available}; then
  echo "${reset}"
  echo -ne "Checking go files formatting... "
  unformatted=$(goimports -l src/app/backend)
  if [ ! -z "$unformatted" ]; then
    echo "${red}ERROR!"
    echo "There is an issue with file formatting."
    echo "To format go files run:"
    echo "  goimports -w src/app/backend"
    exit_code=1
  else
    echo "${green}OK"
  fi
fi

echo -ne "${reset}\n"
if [[ "${exit_code}" != 0 ]]; then
  echo "${red}Aborting commit${reset}"
fi
exit ${exit_code}

# ex: ts=2 sw=2 et filetype=sh
